package com.hx.mypetstore.ui.my;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.hx.mypetstore.Bean.VipBean;
import com.hx.mypetstore.R;
import com.hx.mypetstore.constant.SPConstants;
import com.hx.mypetstore.network.HttpURL;
import com.hx.mypetstore.ui.Address.AddressActivity;
import com.hx.mypetstore.ui.myInfo.MyInfoActivity;
import com.hx.mypetstore.ui.order.OrderActivity;
import com.hx.mypetstore.ui.setting.SettingActivity;
import com.hx.mypetstore.util.SPUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class myCentFragment extends Fragment {

    private static final String TAG = "myCentFragment";

    // 头像
    private ImageView mIvHeadImg;
    // 成为会员
    private TextView mTvMembers;
    // 会员-时间
    private TextView mTvMembersTime, mTvNickName;
    // 会员卡
    private LinearLayout mLlMemberLayout;
    // 会员卡 - 图标
    private ImageView mIvMemberImg;
    // 会员卡 - 名称
    private TextView mTvMemberName;
    // 会员卡 - 描述
    private TextView mTvMemberDesc;
    // 会员卡 - 立即续费
    private TextView mTvMemberPay;

    private Context mcontext;

    /**
     * 用于从网络初始化UI的handler
     */
    private Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    Toast.makeText(mcontext,"请求失败",Toast.LENGTH_LONG);
                    break;
                case 1:
                        Integer vip =(Integer) SPUtil.get(mcontext, SPConstants.VIPBEAN, 1);
                        mTvMemberDesc.setText("会员积分:"+vip);
                        mTvMembers.setText("已是会员！");
                    break;
                case 3:
                    mTvMemberDesc.setText("不是会员");
                    mTvMembers.setText("成为会员");
                default:
                    break;
            }
        }
    };


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fg_my_cent,container,false);
        mcontext = getContext();
        // 初始化View
        initView(view);
        return view;
    }

    private void initView(View view) {
        //别名
        mTvNickName = view.findViewById(R.id.name_view);
        // 头像
        mIvHeadImg = view.findViewById(R.id.mine_headImg);
        // 成为会员
        mTvMembers = view.findViewById(R.id.mine_members);
        // 会员-时间
        mTvMembersTime = view.findViewById(R.id.mine_members_time);
        // 会员卡
        mLlMemberLayout = view.findViewById(R.id.mine_member_layout);
        // 会员卡 - 图标
        mIvMemberImg = view.findViewById(R.id.mine_member_icon);
        // 会员卡 - 名称
        mTvMemberName = view.findViewById(R.id.mine_member_name);
        // 会员卡 - 描述
        mTvMemberDesc = view.findViewById(R.id.mine_member_desc);
        // 会员卡 - 立即续费
        mTvMemberPay = view.findViewById(R.id.mine_member_pay);
        initData();
        view.findViewById(R.id.title_right).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 设置
                startActivity(new Intent(getActivity(), SettingActivity.class));
            }
        });


        view.findViewById(R.id.mine_orders).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 我的订单
                startActivity(new Intent(getActivity(), OrderActivity.class));
            }
        });

        view.findViewById(R.id.mine_addressManage).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到地址管理界面
                startActivity(new Intent(getActivity(), AddressActivity.class));

            }
        });
        view.findViewById(R.id.my_info).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), MyInfoActivity.class);
                startActivity(intent);
            }
        });
        //注册成为会员
        mTvMembers.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Integer key = (Integer)SPUtil.get(mcontext, SPConstants.KEY_VIP, 1);
                if(key == 1){
                    Toast.makeText(mcontext,"你已是会员",Toast.LENGTH_LONG).show();
                }else{
                    registerVip();
                }
            }
        });

        haveVip();
    }

    private void registerVip() {
        String url = HttpURL.TOVIP;
        //发送请求
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("userid", SPUtil.get(mcontext,SPConstants.KEY_LOCAL_USER,"").toString())
                .add("vip","1")
                .add("account","1000")
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    Message message = Message.obtain();
                    if(!jsonObject.getBoolean("success"))
                        message.what = 0;
                    else{
                        Gson gson = new Gson();
                        VipBean vip = gson.fromJson(jsonObject.getString("data"), VipBean.class);
                        Log.e(TAG, "vip"+vip );
                        SPUtil.put(mcontext,SPConstants.KEY_VIP,vip.getVip());
                        SPUtil.put(mcontext,SPConstants.VIPBEAN,vip.getAccount());
                        message.what =  1;
                     //   Log.e(TAG, "onResponse: "+SPUtil.get(mcontext,SPConstants.KEY_VIP,"") );
                    }
                    uiHandler.sendMessage(message);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void initData() {
        String nickName = (String) SPUtil.get(getActivity(), SPConstants.KEY_NICK_NAME, "");
        if (TextUtils.isEmpty(nickName)) {
            return;
        }
        // 昵称
        mTvNickName.setText(nickName);

        boolean isHuaweiLogin = (boolean) SPUtil.get(getActivity(), SPConstants.KEY_HW_LOGIN, false);
        if (!isHuaweiLogin) {
            return;
        }

        String openId = (String) SPUtil.get(getActivity(), SPConstants.KEY_HW_OEPNID, "");
        if (TextUtils.isEmpty(openId)) {
            // 无本地保存的个人信息数据
            return;
        }

        String userInfo = (String) SPUtil.get( getActivity(), openId, "");
        if (TextUtils.isEmpty(userInfo)) {
            // 无本地保存的个人信息数据
            return;
        }

        // 头像
        String headPhoto = "";
        try {
            JSONObject jsonObject = new JSONObject(userInfo);
            headPhoto = jsonObject.optString(SPConstants.KEY_HEAD_PHOTO, "");
        } catch (JSONException ignored) {
            Log.e(TAG, "initData JSONException");
        }
        if (!TextUtils.isEmpty(headPhoto)) {
            Glide.with(this)
                    .load(headPhoto)
                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                    .into(mIvHeadImg);
        }
    }

    private void haveVip() {
        String url = HttpURL.HAVEVIP;
        Log.e(TAG, "调用成功" );
        //发送请求
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("userid",  SPUtil.get(mcontext,SPConstants.KEY_LOCAL_USER,"").toString())
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: " + e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    Message message = Message.obtain();
//                    Log.e(TAG, "key"+jsonObject.getBoolean("data") );
                    if(!jsonObject.getBoolean("success")) {
                        SPUtil.put(mcontext,SPConstants.KEY_VIP,0);
                        message.what = 3;
                    }
                    else{
                        Gson gson = new Gson();
                        VipBean vip = gson.fromJson(jsonObject.getString("data"), VipBean.class);
                        Log.e(TAG, "是否成为vip"+vip );
                        SPUtil.put(mcontext,SPConstants.KEY_VIP,vip.getVip());
                        SPUtil.put(mcontext,SPConstants.VIPBEAN,vip.getAccount());
                        message.what =  1;
                    }
                    uiHandler.sendMessage(message);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        boolean isLogin = (boolean) SPUtil.get(getActivity(), SPConstants.KEY_LOGIN, false);
        if (!isLogin) {
            getActivity().finish();
        }
    }
}